﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Text.RegularExpressions;

namespace AliCMS.AdModule.OleDb
{
    public class SubInstance : OleDbBase, Dal.ISubInstance
    {
        public int GetInnerIDFromGuid(Guid guid)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.SubInstance.ID, MapType(Alias.SubInstance.ID)).Value = guid;
            Command.CommandText = "SELECT " + MapColumn(Alias.SubInstance.InnerID) + " FROM " + MapTable(Alias.Objects.SubInstance) + " WHERE " + MapColumn(Alias.SubInstance.ID) + "=?";
            object result = Command.ExecuteScalar();
            if (result == null)
                return 0;
            else
                return (int)result;
        }
        public Guid GetGuidFromInnerID(object id)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.SubInstance.InnerID, MapType(Alias.SubInstance.InnerID)).Value = id;
            Command.CommandText = "SELECT " + MapColumn(Alias.SubInstance.ID) + " FROM " + MapTable(Alias.Objects.SubInstance) + " WHERE " + MapColumn(Alias.SubInstance.InnerID) + "=?";
            object result = Command.ExecuteScalar();
            if (result == null)
                return Guid.Empty;
            else
                return (Guid)result;
        }
        public Dictionary<string, object> Get(object id)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();

            StringBuilder sql = new StringBuilder("SELECT TOP 1");
            sql.Append(" " + MapColumn(Alias.SubInstance.ID));
            sql.Append("," + MapColumn(Alias.SubInstance.InnerID));
            sql.Append("," + MapColumn(Alias.SubInstance.Name));
            sql.Append("," + MapColumn(Alias.SubInstance.UserID));
            sql.Append("," + MapColumn(Alias.SubInstance.UserName));
            sql.Append("," + MapColumn(Alias.SubInstance.CreatorID));
            sql.Append("," + MapColumn(Alias.SubInstance.Creator));
            sql.Append("," + MapColumn(Alias.SubInstance.CreateTime));
            sql.Append("," + MapColumn(Alias.SubInstance.IsDeleted));
            sql.Append(" FROM " + MapTable(Alias.Objects.SubInstance));

            if (id is Guid)
            {
                sql.Append(" WHERE " + MapColumn(Alias.SubInstance.ID) + "=?");

                Command.Parameters.Clear();
                Command.Parameters.Add("@" + Alias.SubInstance.ID, MapType(Alias.SubInstance.ID)).Value = id;
            }
            else
            {
                sql.Append(" WHERE " + MapColumn(Alias.SubInstance.InnerID) + "=?");

                Command.Parameters.Clear();
                Command.Parameters.Add("@" + Alias.SubInstance.InnerID, MapType(Alias.SubInstance.InnerID)).Value = id;
            }

            #region HasSelfLimitation
			/*
            Dictionary<string, string> user = Manager.User;
            if (CheckRight)
            {
                if (user != null && Convert.ToBoolean(user["HasSelfLimitation"]))
                {
                    sql.Append(" AND " + MapColumn(Alias.SubInstance.CreatorID) + "=?");
                    Command.Parameters.Add("@" + Alias.SubInstance.CreatorID, MapType(Alias.SubInstance.CreatorID)).Value = new Guid(user["ID"]);
                }
            }
			*/
            #endregion

            Command.CommandText = sql.ToString();
            DataReader = Command.ExecuteReader();
            if (!DataReader.HasRows)
            {
                DataReader.Close();
                return null;
            }

            DataReader.Read();
            int i = 0;
            result[Alias.SubInstance.ID] = DataReader[i++];
            result[Alias.SubInstance.InnerID] = DataReader[i++];
            result[Alias.SubInstance.Name] = DataReader[i++];
            result[Alias.SubInstance.UserID] = DataReader[i++];
            result[Alias.SubInstance.UserName] = DataReader[i++];
            result[Alias.SubInstance.CreatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
            result[Alias.SubInstance.Creator] = DataReader[i++];
            result[Alias.SubInstance.CreateTime] = DataReader[i++];
            result[Alias.SubInstance.IsDeleted] = DataReader[i++];
            DataReader.Close();

            return result;
        }
        public void Add(Dictionary<string, object> item)
        {
            #region 设置RowLang
            item.Add(Alias.SubInstance.RowLang, "|" + Lang + "|");
            #endregion

            StringBuilder names = new StringBuilder();
            StringBuilder values = new StringBuilder();

            Command.Parameters.Clear();
            PrepareParameters(names, values, item);

            Command.CommandText = "INSERT INTO " + MapTable(Alias.Objects.SubInstance) + "(" + names + ") VALUES(" + values + ")";
            Command.ExecuteNonQuery();
        }
        public void Modify(int id, Dictionary<string, object> changes)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.SubInstance.InnerID, MapType(Alias.SubInstance.InnerID)).Value = id;

            #region 检查并设置RowLang
            Command.CommandText = "SELECT " + MapColumn(Alias.SubInstance.RowLang) + " FROM " + MapTable(Alias.Objects.SubInstance) + " WHERE " + MapColumn(Alias.SubInstance.InnerID) + "=?";
            string rowLang = Command.ExecuteScalar().ToString();
            if (!rowLang.Contains("|" + Lang + "|"))
                changes.Add(Alias.SubInstance.RowLang, rowLang + Lang + "|");
            #endregion

            StringBuilder sql = new StringBuilder("UPDATE " + MapTable(Alias.Objects.SubInstance) + " SET ");
            Command.Parameters.Clear();
            PrepareParameters(sql, changes);
            Command.Parameters.Add("@" + Alias.SubInstance.InnerID, MapType(Alias.SubInstance.InnerID)).Value = id;

            sql.Append(" WHERE " + MapColumn(Alias.SubInstance.InnerID) + "=?");

            #region 权限
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null)
                {
                    #region 管理员
                    if (user["Namespace"] == "AliCMS.SystemModule")
                    {
                        if (Convert.ToBoolean(user["HasSelfLimitation"]))
                        {
                            sql.Append(" AND " + MapColumn(Alias.SubInstance.CreatorID) + "=?");
                            Command.Parameters.Add("@" + Alias.SubInstance.CreatorID, MapType(Alias.SubInstance.CreatorID)).Value = new Guid(user["ID"]);
                        }
                    }
                    #endregion
                    #region 用户
                    else
                    {
                        sql.Append(" AND " + MapColumn(Alias.SubInstance.UserID) + "=?");
                        Command.Parameters.Add("@" + Alias.SubInstance.UserID, MapType(Alias.SubInstance.UserID)).Value = new Guid(user["ID"]);
                    }
                    #endregion
                }
            }
            #endregion

            Command.CommandText = sql.ToString();
            Command.ExecuteNonQuery();
        }
        public void Delete(int id)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.SubInstance.InnerID, MapType(Alias.SubInstance.InnerID)).Value = id;

            StringBuilder sql = new StringBuilder("DELETE FROM " + MapTable(Alias.Objects.SubInstance) + " WHERE " + MapColumn(Alias.SubInstance.InnerID) + "=?");

            #region 权限
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null)
                {
                    #region 管理员
                    if (user["Namespace"] == "AliCMS.SystemModule")
                    {
                        if (Convert.ToBoolean(user["HasSelfLimitation"]))
                        {
                            sql.Append(" AND " + MapColumn(Alias.SubInstance.CreatorID) + "=?");
                            Command.Parameters.Add("@" + Alias.SubInstance.CreatorID, MapType(Alias.SubInstance.CreatorID)).Value = new Guid(user["ID"]);
                        }
                    }
                    #endregion
                    #region 用户
                    else
                    {
                        sql.Append(" AND " + MapColumn(Alias.SubInstance.UserID) + "=?");
                        Command.Parameters.Add("@" + Alias.SubInstance.UserID, MapType(Alias.SubInstance.UserID)).Value = new Guid(user["ID"]);
                    }
                    #endregion
                }
            }
            #endregion

            Command.CommandText = sql.ToString();
            Command.ExecuteNonQuery();
        }
        public DataTable List(int page, int pageSize, string condition, string sort)
        {
            DataTable result = new DataTable();
            result.Columns.Add(Alias.SubInstance.ID, MapCSType(Alias.SubInstance.ID));
            result.Columns.Add(Alias.SubInstance.InnerID, MapCSType(Alias.SubInstance.InnerID));
            result.Columns.Add(Alias.SubInstance.Name, MapCSType(Alias.SubInstance.Name));
            result.Columns.Add(Alias.SubInstance.UserID, MapCSType(Alias.SubInstance.UserID));
            result.Columns.Add(Alias.SubInstance.UserName, MapCSType(Alias.SubInstance.UserName));
            result.Columns.Add(Alias.SubInstance.CreatorID, MapCSType(Alias.SubInstance.CreatorID));
            result.Columns.Add(Alias.SubInstance.Creator, MapCSType(Alias.SubInstance.Creator));
            result.Columns.Add(Alias.SubInstance.CreateTime, MapCSType(Alias.SubInstance.CreateTime));
            result.Columns.Add(Alias.SubInstance.IsDeleted, MapCSType(Alias.SubInstance.IsDeleted));

            #region 条件
            Command.Parameters.Clear();
            StringBuilder where = new StringBuilder();
            if (!String.IsNullOrEmpty(condition))
            {
                where.Append(" WHERE " + Alias.SubInstance.RowLang + " LIKE '%|" + Lang + "|%' AND ");
                where.Append("(" + condition + ")");

                ParseCondition(where, "");
            }
            else
            {
                where.Append(" WHERE " + MapColumn(Alias.SubInstance.RowLang) + " LIKE '%|" + Lang + "|%'");
            }

            #region 权限
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null)
                {
                    #region 管理员
                    if (user["Namespace"] == "AliCMS.SystemModule")
                    {
                        if (Convert.ToBoolean(user["HasSelfLimitation"]))
                        {
                            if (where.Length > 0)
                                where.Append(" AND ");

                            where.Append(MapColumn(Alias.SubInstance.CreatorID) + "=?");
                            Command.Parameters.Add("@" + Alias.SubInstance.CreatorID, MapType(Alias.SubInstance.CreatorID)).Value = new Guid(user["ID"]);
                        }
                    }
                    #endregion
                    #region 用户
                    else
                    {
                        #region 限于自己
                        if (where.Length > 0)
                            where.Append(" AND ");

                        where.Append(MapColumn(Alias.SubInstance.CreatorID) + "=?");
                        Command.Parameters.Add("@" + Alias.SubInstance.CreatorID, MapType(Alias.SubInstance.CreatorID)).Value = new Guid(user["ID"]);
                        #endregion
                    }
                    #endregion
                }
            }
            #endregion
            #endregion

            #region 排序
            if (!String.IsNullOrEmpty(sort))
                sort = " ORDER BY " + ParseSort(sort, "");
            else
                sort = " ORDER BY " + MapColumn(Alias.SubInstance.InnerID) + " DESC";
            #endregion

            #region 构造SQL语句
            StringBuilder sql = new StringBuilder("SELECT");
            if (page > 0 && pageSize > 0)
                sql.Append(" TOP " + (page * pageSize));
            sql.Append(" " + MapColumn(Alias.SubInstance.ID));
            sql.Append("," + MapColumn(Alias.SubInstance.InnerID));
            sql.Append("," + MapColumn(Alias.SubInstance.Name));
            sql.Append("," + MapColumn(Alias.SubInstance.UserID));
            sql.Append("," + MapColumn(Alias.SubInstance.UserName));
            sql.Append("," + MapColumn(Alias.SubInstance.CreatorID));
            sql.Append("," + MapColumn(Alias.SubInstance.Creator));
            sql.Append("," + MapColumn(Alias.SubInstance.CreateTime));
            sql.Append("," + MapColumn(Alias.SubInstance.IsDeleted));
            sql.Append(" FROM " + MapTable(Alias.Objects.SubInstance));
            sql.Append(where + sort);
            Command.CommandText = sql.ToString();
            #endregion

            #region 执行SQL语句并获取记录
            int curIndex = 0, rowIndex = 0;
            int startIndex = (page - 1) * pageSize;
            DataReader = Command.ExecuteReader();
            while (DataReader.Read())
            {
                if (pageSize != -1)
                {
                    if (curIndex < startIndex)
                    {
                        curIndex++;
                        continue;
                    }

                    if (rowIndex == pageSize)
                        break;
                }

                DataRow row = result.NewRow();
                int i = 0;
                row[Alias.SubInstance.ID] = DataReader[i++];
                row[Alias.SubInstance.InnerID] = DataReader[i++];
                row[Alias.SubInstance.Name] = DataReader[i++];
                row[Alias.SubInstance.UserID] = DataReader[i++];
                row[Alias.SubInstance.UserName] = DataReader[i++];
                row[Alias.SubInstance.CreatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
                row[Alias.SubInstance.Creator] = DataReader[i++];
                row[Alias.SubInstance.CreateTime] = DataReader[i++];
                row[Alias.SubInstance.IsDeleted] = DataReader[i++];
                result.Rows.Add(row);

                rowIndex++;
            }
            DataReader.Close();
            #endregion

            return result;
        }
        public int GetRecordCount(string condition)
        {
            #region 条件
            Command.Parameters.Clear();
            StringBuilder where = new StringBuilder();
            if (!String.IsNullOrEmpty(condition))
            {
                where.Append(" WHERE " + Alias.SubInstance.RowLang + " LIKE '%|" + Lang + "|%' AND ");
                where.Append("(" + condition + ")");

                ParseCondition(where, "");
            }
            else
            {
                where.Append(" WHERE " + MapColumn(Alias.SubInstance.RowLang) + " LIKE '%|" + Lang + "|%'");
            }

            #region 权限
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null)
                {
                    #region 管理员
                    if (user["Namespace"] == "AliCMS.SystemModule")
                    {
                        if (Convert.ToBoolean(user["HasSelfLimitation"]))
                        {
                            if (where.Length > 0)
                                where.Append(" AND ");

                            where.Append(MapColumn(Alias.SubInstance.CreatorID) + "=?");
                            Command.Parameters.Add("@" + Alias.SubInstance.CreatorID, MapType(Alias.SubInstance.CreatorID)).Value = new Guid(user["ID"]);
                        }
                    }
                    #endregion
                    #region 用户
                    else
                    {
                        #region 限于自己
                        if (where.Length > 0)
                            where.Append(" AND ");

                        where.Append(MapColumn(Alias.SubInstance.CreatorID) + "=?");
                        Command.Parameters.Add("@" + Alias.SubInstance.CreatorID, MapType(Alias.SubInstance.CreatorID)).Value = new Guid(user["ID"]);
                        #endregion
                    }
                    #endregion
                }
            }
            #endregion
            #endregion

            Command.CommandText = "SELECT COUNT(*) FROM " + MapTable(Alias.Objects.SubInstance) + where;
            return Convert.ToInt32(Command.ExecuteScalar());
        }
    }
}
